<template>
  <div>
    <el-dialog
        :visible.sync="registerVisible"
        width="25%"
        class="register_dialog"
        center
        @close="close"
        :close-on-click-modal="false"
    >
      <div class="login">
        <h2 class="login-title">
          {{title}}
        </h2>
        <el-form
            ref="form"
            :rules="rule"
            :model="registerFrom"
            label-width="80px"
            :hide-required-asterisk="true"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model="registerFrom.username" clearable/>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="registerFrom.password" show-password clearable/>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="registerVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleRegister">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import {register} from "@/api/user";
export default {
  name: "index",
  watch:{
    $route: {
      handler: function(route) {
        this.redirect = route.path
      },
      immediate: true
    }
  },
  data() {
    return {
      registerVisible:false,
      registerFrom:{},
      title:'账号注册',
      rule:{
        username:[
          {required:true,message:'账号不能为空',trigger:'blur'}
        ],
        password:[
          {required:true,message:'密码不能为空',trigger:'blur'}
        ]
      },
      redirect: undefined
    }
  },
  methods:{
    reset() {
      this.registerFrom = {
        username:undefined,
        password:undefined
      }
    },
    close() {
      this.reset()
      this.$refs.form.resetFields()
    },
    handleRegister() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.$store.dispatch('login',this.loginFrom).then(() => {
          //   this.$store.dispatch('getInfo')
          //   this.$router.push({path:this.redirect || '/'})
          //   this.loginVisible = false
          // }).catch((err) => {
          //   console.log(err)
          // })
          register(this.registerFrom).then(res => {
            if (res.code === 200) {
              this.$modal.msgSuccess('注册成功，即将登录...')
              this.$store.dispatch('login',this.registerFrom).then(() => {
                this.$store.dispatch('getInfo')
                this.$router.push({path:this.redirect || '/'})
                this.registerVisible = false
              }).catch((err) => {
                console.log(err)
              })
            }
          }).catch((err) => {
            console.log(err)
          })
        }
      })
    }
  }
}
</script>

<style>
.login-title {
  text-align: center;
}

.register_dialog  .el-dialog__header{
  padding: 0 !important;
}
.register_dialog .el-dialog {
  border-radius: 15px;
}
</style>
